BEST FF SO FAR

/**
 * This function creates a modal dialog that allows the user to toggle feature flags.
 * It retrieves the feature flags from the session storage, creates checkboxes for each flag,
 * and saves the updated flags back to the session storage when the user clicks the save button.
 * The modal dialog is appended to the document body and can be closed by clicking the save button.
 * 
 * Requires the use of utils/bookmarkletMaker.js to generate the bookmarklet.
 */
let data = sessionStorage.getItem('rbc_di_session');
let parsedData = JSON.parse(data);
let features = parsedData.features || {};

let modal = document.createElement('div');
modal.className = 'rbc-feature-flags-modal';
modal.style.cssText = `
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	background-color: #ffffff;
	border-radius: 8px;
	box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
	z-index: 9999;
	width: 90%;
	max-height: 80vh;
	overflow-y: auto;
	font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
	font-size: 14px;
	line-height: 1.5;
`;

// Add modal header
let modalHeader = document.createElement('div');
modalHeader.style.cssText = `
	position: sticky;
	top: 0;
	padding: 24px 24px 0 24px;
	border-bottom: 1px solid #e6e6e6;
	background-color: #ffffff;
	z-index: 1;
`;

let headerTitle = document.createElement('h1');
headerTitle.innerText = 'Feature Flags Manager';
headerTitle.style.cssText = `
	margin: 0 0 16px 0;
	font-size: 24px;
	font-weight: 600;
	color: #333333;
	line-height: 1.3;
`;

modalHeader.appendChild(headerTitle);
modal.appendChild(modalHeader);

// Container for new features (moved to top)
let newFeaturesSection = document.createElement('div');
newFeaturesSection.style.cssText = `
	padding: 0 24px 24px 24px;
	border-bottom: 1px solid #e6e6e6;
	margin-bottom: 24px;
`;

let newFeatureTitle = document.createElement('h3');
newFeatureTitle.innerText = 'Add New Feature Flags';
newFeatureTitle.style.cssText = `
	margin: 0 0 16px 0;
	font-size: 18px;
	font-weight: 600;
	color: #333333;
`;
newFeaturesSection.appendChild(newFeatureTitle);

// Two-column container for inputs and suggestions
let twoColumnContainer = document.createElement('div');
twoColumnContainer.style.cssText = `
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 24px;
`;

// Left column - Container for all new feature inputs
let leftColumn = document.createElement('div');
let newFeaturesContainer = document.createElement('div');
newFeaturesContainer.id = 'newFeaturesContainer';
leftColumn.appendChild(newFeaturesContainer);

// Function to create a new feature input row
function createNewFeatureRow() {
	let newFeatureContainer = document.createElement('div');
	newFeatureContainer.className = 'new-feature-row';
	newFeatureContainer.style.cssText = `
		display: flex;
		align-items: center;
		gap: 12px;
		margin-bottom: 12px;
		padding: 12px;
		border: 1px solid #e6e6e6;
		border-radius: 6px;
		background-color: #fafafa;
	`;

	let newFeatureCheckbox = document.createElement('input');
	newFeatureCheckbox.type = 'checkbox';
	newFeatureCheckbox.checked = true;
	newFeatureCheckbox.className = 'new-feature-checkbox';
	newFeatureCheckbox.style.cssText = `
		width: 16px;
		height: 16px;
		accent-color: #006ac3;
	`;

	let newFeatureInput = document.createElement('input');
	newFeatureInput.type = 'text';
	newFeatureInput.placeholder = 'Enter feature flag name...';
	newFeatureInput.className = 'new-feature-input';
	newFeatureInput.style.cssText = `
		flex: 1;
		padding: 8px 12px;
		border: 1px solid #d1d5db;
		border-radius: 4px;
		font-size: 14px;
		font-family: inherit;
		transition: border-color 0.2s ease;
	`;
	
	newFeatureInput.addEventListener('focus', function() {
		this.style.borderColor = '#006ac3';
		this.style.outline = 'none';
	});
	
	newFeatureInput.addEventListener('blur', function() {
		this.style.borderColor = '#d1d5db';
	});
	newFeatureInput.addEventListener('keydown', handleNewFeatureInputKeydown); // Attach keydown listener

	let removeButton = document.createElement('button');
	removeButton.innerText = 'Remove';
	removeButton.style.cssText = `
		padding: 6px 12px;
		background-color: transparent;
		color: #666666;
		border: 1px solid #d1d5db;
		border-radius: 4px;
		font-size: 12px;
		cursor: pointer;
		transition: all 0.2s ease;
	`;
	
	removeButton.addEventListener('mouseenter', function() {
		this.style.backgroundColor = '#ffebee';
		this.style.borderColor = '#d32f2f';
		this.style.color = '#d32f2f';
	});
	
	removeButton.addEventListener('mouseleave', function() {
		this.style.backgroundColor = 'transparent';
		this.style.borderColor = '#d1d5db';
		this.style.color = '#666666';
	});
	
	removeButton.addEventListener('click', function() {
		newFeatureContainer.remove();
	});

	newFeatureContainer.appendChild(newFeatureCheckbox);
	newFeatureContainer.appendChild(newFeatureInput);
	newFeatureContainer.appendChild(removeButton);

	return newFeatureContainer;
}

// Add initial new feature row
newFeaturesContainer.appendChild(createNewFeatureRow());

// Add button to add more feature rows
let addFeatureButton = document.createElement('button');
addFeatureButton.innerText = '+ Add Another Feature Flag';
addFeatureButton.style.cssText = `
	padding: 8px 16px;
	background-color: transparent;
	color: #006ac3;
	border: 1px solid #006ac3;
	border-radius: 4px;
	font-size: 14px;
	cursor: pointer;
	margin-top: 8px;
	transition: all 0.2s ease;
`;

addFeatureButton.addEventListener('mouseenter', function() {
	this.style.backgroundColor = '#f3f7f8';
});

addFeatureButton.addEventListener('mouseleave', function() {
	this.style.backgroundColor = 'transparent';
});

addFeatureButton.addEventListener('click', function() {
	newFeaturesContainer.appendChild(createNewFeatureRow());
	attachKeydownListenerToNewFeatureInputs();
});

leftColumn.appendChild(addFeatureButton);

// Right column - Create suggestions column
let suggestionsColumn = document.createElement('div');
suggestionsColumn.style.cssText = `
	padding: 12px;
	border: 1px solid #e6e6e6;
	border-radius: 6px;
	background-color: #fafafa;
	overflow-y: auto;
	max-height: 200px;
`;

let suggestionsTitle = document.createElement('h3');
suggestionsTitle.innerText = 'Suggestions';
suggestionsTitle.style.cssText = `
	margin: 0 0 12px 0;
	font-size: 16px;
	font-weight: 600;
	color: #333333;
`;
suggestionsColumn.appendChild(suggestionsTitle);

let suggestionsList = document.createElement('div');
suggestionsList.id = 'suggestionsList';
suggestionsColumn.appendChild(suggestionsList);

// Add columns to two-column container
twoColumnContainer.appendChild(leftColumn);
twoColumnContainer.appendChild(suggestionsColumn);

// Add two-column container to the section
newFeaturesSection.appendChild(twoColumnContainer);
modal.appendChild(newFeaturesSection);

// Load suggestions from local storage
let savedFlags = JSON.parse(localStorage.getItem('savedFeatureFlags') || '[]');

// Initialize suggestions section with predefined feature flags
let initialSuggestions = [
	'marketsResearchWebComponent',
	'rcSectorAndEvents',
	'rcMarkemovers',
	'rcBreakingNews',
	'rcReportsAndCommentary',
	'optionsStrikePriceExperience',
	'useRbcXrefForUs',
	'sentryLogging'
];

// Merge initial suggestions with saved flags
savedFlags = [...new Set([...savedFlags, ...initialSuggestions])];
localStorage.setItem('savedFeatureFlags', JSON.stringify(savedFlags));

// Populate suggestions list
savedFlags.forEach(flag => {
	let suggestionItem = document.createElement('button');
	suggestionItem.innerText = flag;
	suggestionItem.style.cssText = `
		padding: 6px 12px;
		margin-bottom: 6px;
		margin-right: 6px;
		background-color: transparent;
		color: #006ac3;
		border: 1px solid #006ac3;
		border-radius: 4px;
		font-size: 12px;
		cursor: pointer;
		transition: all 0.2s ease;
		display: inline-block;
		width: 100%;
		text-align: left;
	`;

	suggestionItem.addEventListener('mouseenter', function() {
		this.style.backgroundColor = '#f3f7f8';
	});

	suggestionItem.addEventListener('mouseleave', function() {
		this.style.backgroundColor = 'transparent';
	});

	suggestionItem.addEventListener('click', function() {
		let newRow = createNewFeatureRow();
		newRow.querySelector('.new-feature-input').value = flag;
		newFeaturesContainer.appendChild(newRow);
		attachKeydownListenerToNewFeatureInputs();
	});

	suggestionsList.appendChild(suggestionItem);
});

// Save new feature flags to local storage
function saveFeatureFlagToLocalStorage(flag) {
	if (!savedFlags.includes(flag)) {
		savedFlags.push(flag);
		localStorage.setItem('savedFeatureFlags', JSON.stringify(savedFlags));
	}
}

// Define saveButton earlier in the code
let saveButton = document.createElement('button');
saveButton.innerText = 'Save Changes';
saveButton.style.cssText = `
	padding: 12px 24px;
	background-color: #006ac3;
	color: #ffffff;
	border: 2px solid #006ac3;
	border-radius: 4px;
	font-size: 14px;
	font-weight: 500;
	cursor: pointer;
	transition: all 0.2s ease;
`;

saveButton.addEventListener('mouseenter', function() {
	this.style.backgroundColor = '#0051a5';
	this.style.borderColor = '#0051a5';
});

saveButton.addEventListener('mouseleave', function() {
	this.style.backgroundColor = '#006ac3';
	this.style.borderColor = '#006ac3';
});

// Update save button to store new flags in local storage
saveButton.addEventListener('click', function() {
	const newFeatureRows = modal.querySelectorAll('.new-feature-row');
	newFeatureRows.forEach(function(row) {
		const input = row.querySelector('.new-feature-input');
		if (input.value && input.value.trim() !== '') {
			saveFeatureFlagToLocalStorage(input.value.trim());
		}
	});
});

// Action buttons container
let actionButtons = document.createElement('div');
actionButtons.style.cssText = `
	position: sticky;
	bottom: 0;
	padding: 24px;
	border-top: 1px solid #e6e6e6;
	display: flex;
	justify-content: flex-end;
	gap: 12px;
	background-color: #fafafa;
	border-radius: 0 0 8px 8px;
`;

// Append actionButtons to the modal later in the code
modal.appendChild(actionButtons);

// Append saveButton to actionButtons after its definition
actionButtons.appendChild(saveButton);

// Existing Features Section
let existingFeaturesHeader = document.createElement('h3');
existingFeaturesHeader.innerText = 'Existing Feature Flags';
existingFeaturesHeader.style.cssText = `
	margin: 0 0 16px 0;
	padding: 0 24px;
	font-size: 18px;
	font-weight: 600;
	color: #333333;
`;
modal.appendChild(existingFeaturesHeader);

// Main content container for existing features
let modalContent = document.createElement('div');
modalContent.style.cssText = `
	padding: 0 24px;
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 16px;
	overflow-y: auto;
	max-height: calc(100vh - (modalHeader.offsetHeight + actionButtons.offsetHeight));
`;

for (let key in features) {
	if (features.hasOwnProperty(key) && typeof features[key] === 'boolean') {
		let checkboxContainer = document.createElement('div');
		checkboxContainer.style.cssText = `
			display: flex;
			align-items: center;
			padding: 12px;
			border: 1px solid #e6e6e6;
			border-radius: 6px;
			transition: all 0.2s ease;
		`;
		
		checkboxContainer.addEventListener('mouseenter', function() {
			this.style.backgroundColor = '#f3f7f8';
			this.style.borderColor = '#006ac3';
		});
		
		checkboxContainer.addEventListener('mouseleave', function() {
			this.style.backgroundColor = '#fafafa';
			this.style.borderColor = '#e6e6e6';
		});

		let checkbox = document.createElement('input');
		checkbox.type = 'checkbox';
		checkbox.id = key;
		checkbox.checked = features[key];
		checkbox.style.cssText = `
			margin-right: 12px;
			width: 16px;
			height: 16px;
			accent-color: #006ac3;
		`;

		let label = document.createElement('label');
		label.htmlFor = key;
		label.innerText = key;
		label.style.cssText = `
			flex: 1;
			font-weight: 400;
			color: #333333;
			cursor: pointer;
			user-select: none;
		`;

		let deleteButton = document.createElement('button');
		deleteButton.innerHTML = '×';
		deleteButton.style.cssText = `
			background: none;
			border: none;
			color: #666666;
			font-size: 18px;
			width: 24px;
			height: 24px;
			border-radius: 50%;
			cursor: pointer;
			display: flex;
			align-items: center;
			justify-content: center;
			transition: all 0.2s ease;
		`;
		
		deleteButton.addEventListener('mouseenter', function() {
			this.style.backgroundColor = '#ffebee';
			this.style.color = '#d32f2f';
		});
		
		deleteButton.addEventListener('mouseleave', function() {
			this.style.backgroundColor = 'transparent';
			this.style.color = '#666666';
		});
		
		deleteButton.addEventListener('click', function() {
			delete features[key];
			checkboxContainer.remove();
		});

		checkboxContainer.appendChild(checkbox);
		checkboxContainer.appendChild(label);
		checkboxContainer.appendChild(deleteButton);
		modalContent.appendChild(checkboxContainer);
	}
}

modal.appendChild(modalContent);

// Close button
let closeButton = document.createElement('button');
closeButton.innerHTML = '×';
closeButton.style.cssText = `
	position: absolute;
	top: 16px;
	right: 16px;
	background: none;
	border: none;
	font-size: 24px;
	color: #666666;
	cursor: pointer;
	width: 32px;
	height: 32px;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.2s ease;
`;

closeButton.addEventListener('mouseenter', function() {
	this.style.backgroundColor = '#f5f5f5';
	this.style.color = '#333333';
});

closeButton.addEventListener('mouseleave', function() {
	this.style.backgroundColor = 'transparent';
	this.style.color = '#666666';
});

closeButton.addEventListener('click', function() {
	document.body.removeChild(modal);
	document.body.removeChild(overlay);
});

let cancelButton = document.createElement('button');
cancelButton.innerText = 'Cancel';
cancelButton.style.cssText = `
	padding: 12px 24px;
	background-color: transparent;
	color: #006ac3;
	border: 2px solid #006ac3;
	border-radius: 4px;
	font-size: 14px;
	font-weight: 500;
	cursor: pointer;
	transition: all 0.2s ease;
`;

cancelButton.addEventListener('mouseenter', function() {
	this.style.backgroundColor = '#f3f7f8';
	this.style.borderColor = '#0051a5';
	this.style.color = '#0051a5';
});

cancelButton.addEventListener('mouseleave', function() {
	this.style.backgroundColor = 'transparent';
	this.style.borderColor = '#006ac3';
	this.style.color = '#006ac3';
});

cancelButton.addEventListener('click', function() {
	document.body.removeChild(modal);
	document.body.removeChild(overlay);
});

actionButtons.appendChild(cancelButton);
actionButtons.appendChild(saveButton);

modal.appendChild(closeButton);
modal.appendChild(actionButtons);

let overlay = document.createElement('div');
overlay.style.cssText = `
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 9998;
	backdrop-filter: blur(2px);
`;

document.body.appendChild(overlay);
document.body.appendChild(modal);

// Close modal on Escape key
function closeFeatureFlagsModal() {
	document.body.removeChild(modal);
	document.body.removeChild(overlay);
	document.removeEventListener('keydown', escListener);
}
function escListener(e) {
	if (e.key === 'Escape') closeFeatureFlagsModal();
}
document.addEventListener('keydown', escListener);

// Update Enter key behavior to create only one new feature flag input
function handleNewFeatureInputKeydown(e) {
	if (e.key === 'Enter' && !e.ctrlKey) {
		// Add a single new feature flag row
		e.preventDefault();
		if (!newFeaturesContainer.querySelector('.new-feature-row:last-child .new-feature-input').value.trim()) {
			return; // Prevent adding a new row if the last input is empty
		}
		newFeaturesContainer.appendChild(createNewFeatureRow());
	} else if (e.key === 'Enter' && e.ctrlKey) {
		// Trigger the Save Changes button
		e.preventDefault();
		saveButton.click();
	}
}

// Attach the keydown listener to all new feature inputs
function attachKeydownListenerToNewFeatureInputs() {
	const newFeatureInputs = modal.querySelectorAll('.new-feature-input');
	newFeatureInputs.forEach(input => {
		input.removeEventListener('keydown', handleNewFeatureInputKeydown); // Remove existing listener to avoid duplicates
		input.addEventListener('keydown', handleNewFeatureInputKeydown);
	});
}

// Ensure listeners are attached after adding new rows
addFeatureButton.addEventListener('click', function() {
	newFeaturesContainer.appendChild(createNewFeatureRow());
	attachKeydownListenerToNewFeatureInputs();
});

// Attach listeners to initial rows
attachKeydownListenerToNewFeatureInputs();

// Add event listener for Enter and Ctrl+Enter in the Add New Feature Flag input
newFeaturesContainer.addEventListener('keydown', function(e) {
	if (e.target.classList.contains('new-feature-input')) {
		if (e.key === 'Enter' && !e.ctrlKey) {
			// Simulate Add Another Feature Flag button click
			newFeaturesContainer.appendChild(createNewFeatureRow());
			e.preventDefault();
		} else if (e.key === 'Enter' && e.ctrlKey) {
			// Simulate Save Changes button click
			saveButton.click();
			e.preventDefault();
		}
	}
});

// Add a style block to isolate bookmarklet styles from the main website
let styleBlock = document.createElement('style');
styleBlock.innerHTML = `
	.rbc-feature-flags-modal input[type="checkbox"] + label::before {
		content: "";
		display: inline-block;
		vertical-align: -25%;
		background-color: transparent;
		height: 26px;
		width: 26px;
		margin: 1px;
		margin-bottom:-1px;
	}
`;

// Append the style block to the modal
modal.appendChild(styleBlock);
